package com.masiyi.easyexcel.service;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.builder.ExcelWriterBuilder;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.alibaba.excel.write.style.column.LongestMatchColumnWidthStyleStrategy;
import com.masiyi.easyexcel.doman.Table;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * @Author masiyi
 * @Date 2023/3/29 14:03
 * @PackageName:com.masiyi.easyexcel.service
 * @ClassName: ExcelService
 * @Description: TODO
 * @Version 1.0
 */
@Service
public class ExcelService {

    @Autowired
    private DataService dataService;

    public static List<WriteSheet> getWriteSheets(List<List<Table>> length) {
        List<WriteSheet> writeSheets = new ArrayList<>();
        for (int i = 0; i < length.size(); i++) {
            WriteSheet writeSheet = EasyExcel.writerSheet(i).registerWriteHandler(new LongestMatchColumnWidthStyleStrategy()).build();
            Table table = length.get(i).get(0);
            writeSheet.setSheetName(table.getTableName());
            writeSheet.setSheetNo(i + 1);
            writeSheets.add(writeSheet);
        }
        return writeSheets;
    }

    public void write() {
        String url = "unicom_iot.xlsx";
        File file = new File(url);
        ExcelWriterBuilder write = EasyExcel.write(file).head(Table.class);
        ExcelWriter build = write.build();
        List<List<Table>> data = dataService.initData();
        List<WriteSheet> writeSheets = getWriteSheets(data);
        for (int i = 0; i < data.size(); i++) {
            List<Table> tables = data.get(i);
            build.write(tables, writeSheets.get(i));
        }
        build.finish();
    }
}
